package es.ikex.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import es.ikex.dao.ProductosDAO;
import es.ikex.modelo.SubirProducto;
import es.ikex.pojo.GeneradorCodigo;

public class AdministracionProducto extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		Iterator<FileItem> iterator = null;
		Map <String,String> datos = new HashMap<String,String>();
		try {
			iterator = upload.parseRequest((RequestContext) request).iterator();
		} catch (FileUploadException e1) {
			e1.printStackTrace();
		}
		File uploadedFile;
		boolean error = false;
		//String dirPath = "C:\\eclipse-jee-muebles\\WorkSpace\\Muebles\\WebContent\\img\\muebles";
		//String dirPath = "C:\\Tomcat7\\webapps\\Muebles\\img\\muebles";
		//String dirPath = "/Muebles/img/muebles";
		String dirPath = "/usr/local/tomcat/webapps/Muebles/img/muebles";
		while (iterator.hasNext()) {
			FileItem item = iterator.next();
			if (!item.isFormField()) {
				String nombre;
				ProductosDAO pdt = new ProductosDAO();
				String c = pdt.getCodigo(datos.get("categoria") + datos.get("coleccion"));
				int a;
				if(c == null || c.equals("")){
					a = 0;
					c = "";
				}else{
					a = Integer.parseInt(c.replaceAll(datos.get("categoria") + datos.get("coleccion"), "0"));
				}
				
				nombre = "";
				try{
					nombre = datos.get("categoria") + datos.get("coleccion") + GeneradorCodigo.getCodigo(c, a) + item.getName().substring(item.getName().lastIndexOf('.'), item.getName().length());
				}catch(StringIndexOutOfBoundsException e){
					error = true;
				}
				String fileNameWithExt = nombre;
				datos.put("foto", fileNameWithExt);
				File filePath = new File(dirPath);
				
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				if(!item.getContentType().equals("image/png")){
					error = true;
					request.setAttribute("error", "La foto tiene que ser una imagen");
				}
				
				uploadedFile = new File(dirPath + "/" + fileNameWithExt);
				if(!error){
					request.removeAttribute("error");
					try {
						item.write(uploadedFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} else {
				if(item.getString().equalsIgnoreCase("")){
					error = true;
					request.setAttribute("error", "Hay algun campo vacio");
				}
				else if(item.getFieldName().indexOf("stock") != -1){
					try{
						Integer.parseInt(item.getString());
					}catch(NumberFormatException e){
						error = true;
						request.setAttribute("error", "El stock debe de ser un numero entero");
					}
				}
				else if(item.getFieldName().equals("precio") || item.getFieldName().equals("alto") || item.getFieldName().equals("ancho") || item.getFieldName().equals("profundidad")){
					try{
						Float.parseFloat(item.getString());
					}catch(NumberFormatException e){
						error = true;
						request.setAttribute("error", "El precio y las medidas deben de ser un numero decimal");
					}
				}
				datos.put(item.getFieldName(), item.getString());
			}
		}
		if(!error){
			SubirProducto.setProducto(datos);
			request.getRequestDispatcher("Admin/modificacionOk.jsp").forward(request, response);
		}else{
			
			request.getRequestDispatcher("Admin/nuevoProducto.jsp").forward(request, response);
		}
	}

}
